package com.viaje.action;

import java.util.Map;

import javax.persistence.EntityManager;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.validator.annotations.*;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.viaje.common.util.Utilitario;
import com.viaje.model.User;


@Action(value = "/login", results = {
		@Result(name = "exito",type="tiles",location = "inicio.tiles"),
		@Result(name = "error", location = "/log/login.jsp"),
		@Result(name = "input", location = "/log/login.jsp") })
public class LoginAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	
	private User user;
	private String message;
	
	@Validations(
		       requiredStrings =
		        	{  @RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "user.account", key = "login.user.account.required"),
		    		   @RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "user.password", key = "login.user.password.required")},
		    	stringLengthFields =
                   {@StringLengthFieldValidator(type = ValidatorType.SIMPLE, trim = true, minLength="6" , maxLength = "10", fieldName = "user.password", key = "login.user.password.length")}
		    )

	public String execute(){
		String result="exito";
		EntityManager em=
				Utilitario.getInstance().getEntityManager();
		User userdb=em.find(User.class, user.getAccount());
		if(userdb!= null){
			if(userdb.getPassword().equals(user.getPassword())){
				Map session = ActionContext.getContext().getSession();
				user.setNickname(userdb.getNickname());
			}else{
				message=getText("login.message.error.passwordincorrect");
				result="error";
			}
		}else{
			message=getText("login.message.error.usernotexist");
			result="error";
		}
		return result;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}

